# encoding:utf-8
import sys, os, time, hmac, requests, base64, json
sys.path.append('..')
from hashlib import sha1
from spider.common import OSS_UPLOAD_URL, OSS_APPID, OSS_APPSECRET
from six.moves.urllib.parse import urlparse
upload_url = OSS_UPLOAD_URL
APPID = OSS_APPID
APPSECRET = OSS_APPSECRET


def getbytes(input_str):
    str_t = bytes(input_str, encoding='utf8')
    return str_t


def generate_stoken():
    ts = int(time.time()) * 1000
    auth = "w"
    stoid = ""
    independence = 0
    num = 1
    version = "1"
    product = "oss"
    company = "syswin"
    appId = APPID  # ## app_id:1015
    appSecret = APPSECRET  # ## accessKeySecret:cfdb9af543e79a5c5fa1d555926af2ba
    appSecret = appSecret.strip()
    securityTokenType = company + "-" + product + "-" + version + "-" + str(num) + "-" + str(independence)
    plaintext = securityTokenType + "\n" + str(appId) + "\n" + str(ts) + "\n" + auth + "\n" + stoid
    my_sign = hmac.new(getbytes(appSecret), getbytes(plaintext), sha1).digest()
    my_sign = str(base64.urlsafe_b64encode(my_sign), 'utf-8')
    stoken = securityTokenType + ":" + str(base64.urlsafe_b64encode(getbytes(plaintext)), 'utf-8').replace('=', '') + ":" + my_sign.replace('=', '')
    return stoken


def create_header(link):
    Host = urlparse(link).netloc
    headers = {
#             "Host":"fast.scloud.systoon.com",
            "Host":Host,
            "stoken":generate_stoken(),
            "Accept-Encoding":"gzip, deflate",
            "Accept":"*/*",
            "Connection":"keep-alive"
            }
    return headers


def get_data(suffix):
    data = {"pub":"1",
            "suffix":suffix,
            "trace_reserve_mark":"f18c3721-62bf-4f41-a0t9-2dce6e552213"
            }

    return data


def upload_to_oss(file_path):
    if os.path.exists(file_path):
        suffiix = '.' + file_path.split('.')[-1]
        file = {'file':open(file_path, 'rb')}
        req = None
        try:
            req = requests.post(upload_url, headers=create_header(upload_url), files=file, data=get_data(suffiix))
            pubUrl = json.loads(req.text)['pubUrl']
            return pubUrl
        except (requests.exceptions.ConnectTimeout, requests.exceptions.Timeout, requests.exceptions.TooManyRedirects):
            print('Please check the network.') 
        except json.decoder.JSONDecodeError:
            print(req.text) 


if __name__ == '__main__':
    pass
